#include "cstr.h"

cstr_t cstr_init(const char* init, int str_size){
    cstr_t cstr_;
    cstr_.start = (char*)malloc(str_size);
    memset(cstr_.start, 0, str_size);
    if(init){
        // strcpy_s(cstr_.start, cstr_.size, init);
        strcpy(cstr_.start, init);
    }
    cstr_.size = str_size;
    return cstr_;
}

cstr_t cstr(const char* init){
    return cstr_init(init, strlen(init) + 1);
}

void cstr_free(cstr_t str){
    free(str.start);
    str.start = nullptr;
    str.size = 0;
}

int cstr_len(cstr_t string){
    // return strnlen_s(dest.start, dest.size);
    return strlen(string.start);
}

void debug_cstr(cstr_t string){
    if(nullptr == string.start){
        printf("--> The cstr_t object is NULL\n");
        return;
    }
    printf("cstr_t --> %s\n", string.start);
    printf("--> size of cstr_t : %zu/%d.\n", strlen(string.start), string.size);
}

// when the work success, dest.start is removed, and return a new cstr_t object.
cstr_t cstr_join(cstr_t dest, cstr_t str2){
    if(dest.size - cstr_len(dest) <= cstr_len(str2)){
        dest.size += str2.size;
        dest.start = realloc(dest.start, dest.size);
        if(!dest.start){
            assert("Fail to realloc\n");
        }
        // else{
        //     printf("Success join the two cstr_t\n");
        // }
    }
    strcat(dest.start, str2.start);
    debug_cstr(dest);
    return dest;
}
